package com.relytosoft.mizar.media.display.services.service.impl;

import com.relytosoft.dubhe.common.core.exception.ServiceException;
import com.relytosoft.dubhe.common.core.object.ResponseResult;
import com.relytosoft.dubhe.common.redis.utils.RedisUtil;
import com.relytosoft.mizar.media.camera.api.entity.CameraPlatform;
import com.relytosoft.mizar.media.camera.api.feign.CameraFeignInService;
import com.relytosoft.mizar.media.display.api.entity.PtzControl;
import com.relytosoft.mizar.media.display.api.enums.PtzCommand;
import com.relytosoft.mizar.media.display.services.service.PtzControlService;
import com.relytosoft.mizar.media.display.services.utils.ResponseUtils;
import com.relytosoft.mizar.media.external.api.display.request.PtzControlDto;
import com.relytosoft.mizar.media.external.api.display.service.PtzOperationService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Optional;

import static com.relytosoft.mizar.media.display.api.enums.PtzCommand.PTZ_GO_PRESET;


/**
 * 云台控制业务海康实现类
 *
 * @author hj
 * @version 1.0
 * @date 2022/4/7 13:55
 * @ClassName HkPtzControlServiceImpl
 */
@Service
public class PtzControlServiceImpl implements PtzControlService {
    public static final String CONTROL = "Control:";
    @Resource
    private PtzOperationService ptzOperationService;
    @Resource
    private CameraFeignInService cameraFeignInService;

    /**
     * 云台控制
     *
     * @param dto
     * @return boolean
     * @author jgg
     * @date 2022/4/6 15:04
     */
    @Override
    public boolean controlPtz(PtzControl dto) {
        Integer channelId = dto.getChannelId();
        PtzCommand command = dto.getCommand();
        Integer action = dto.getAction();
        //开始对云台进行操作且不是转动云台到指定预置点
        if (action == 0 && !Objects.equals(command,PTZ_GO_PRESET)) {
            Object o= Optional.ofNullable(RedisUtil.get(CONTROL + channelId)).orElse((Object) false);
            boolean flag = (Boolean) o;
            //当前通道云台正在被控制
            if (flag) {
                throw new ServiceException("云台正在被控制！！");
            }else {
                //当前通道云台没有被控制，现置为正在被控制
                RedisUtil.set(CONTROL + channelId,true);
            }
        }else {
            RedisUtil.set(CONTROL + channelId,false);
        }
        ResponseResult<CameraPlatform> result = cameraFeignInService.findById(channelId);
        PtzControlDto hkPtzControlDto = new PtzControlDto(
                ResponseUtils.getCameraIndex(result),
                dto.getAction(),
                dto.getCommand().getHkCommand(),
                dto.getPresetIndex()
        );
        return ptzOperationService.controlPtz(hkPtzControlDto);
    }
}
